<template>
  <div>
    <!-- 标题组件 -->
    <Title :title="title"></Title>
    
    <!-- 文件选择器 -->
    <div class="file-selector">
      <label for="videoFolder" class="btn btn-primary">
        <i class="fa fa-folder-open"></i> 选择视频文件夹
      </label>
      <input 
        id="videoFolder" 
        type="file" 
        ref="fileInput"
        @change="handleFolderSelect"
        multiple 
        webkitdirectory 
        directory 
        accept="video/*"
        class="hidden"
      />
      <div v-if="selectedFolderPath" class="folder-path">
        <i class="fa fa-folder"></i> 已选择: {{ selectedFolderPath }}
      </div>
      <div v-if="errorMessage" class="error-message">
        <i class="fa fa-exclamation-circle"></i> {{ errorMessage }}
      </div>
    </div>
    
    <!-- 视频预览区域 -->
    <div class="video-preview-container">
      <video
        v-if="selectedVideoUrl"
        :src="selectedVideoUrl"
        controls
        class="preview-video"
      ></video>
      <div v-else class="no-video-message">
        <i class="fa fa-film"></i> 请选择视频文件夹并点击图表上的点查看视频预览
      </div>
    </div>
    
    <!-- G2Plot图表容器 -->
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { Line } from '@antv/g2plot';
import Title from './Title.vue';
import { ref, onMounted } from 'vue';

// 组件状态
const title = ref('文件夹视频数据分析');
const chartContainer = ref(null);
const fileInput = ref(null);
const videoData = ref([]);
const selectedVideoUrl = ref('');
const selectedFolderPath = ref('');
const objectURLs = ref([]);
const errorMessage = ref('');

// 视频文件扩展名白名单
const VIDEO_EXTENSIONS = [
  '.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.3gp'
];

// 检查文件是否为视频
const isVideoFile = (file) => {
  // 优先使用MIME类型检测
  if (file.type.startsWith('video/')) return true;
  
  // 其次使用文件扩展名检测
  const ext = file.name.toLowerCase().split('.').pop();
  return VIDEO_EXTENSIONS.includes(`.${ext}`);
};

// 处理文件夹选择
const handleFolderSelect = (event) => {
  errorMessage.value = '';
  const files = event.target.files;
  
  if (!files || files.length === 0) {
    errorMessage.value = '未选择任何文件';
    return;
  }
  
  try {
    // 获取文件夹路径
    let folderPath = '';
    if (files[0].webkitRelativePath) {
      folderPath = files[0].webkitRelativePath.split('/')[0];
    } else {
      // 尝试从文件路径推断文件夹名
      folderPath = files[0].name.split('/')[0] || '未命名文件夹';
    }
    selectedFolderPath.value = folderPath;
    
    // 过滤视频文件
    const videos = Array.from(files).filter(isVideoFile);
    
    if (videos.length === 0) {
      errorMessage.value = '所选文件夹中没有找到视频文件';
      return;
    }
    
    // 处理视频数据
    const processedData = videos.map((file, index) => {
      const url = URL.createObjectURL(file);
      objectURLs.value.push(url);
      
      return {
        name: file.name,
        duration: 0,
        size: file.size / 1024 / 1024,
        url,
        timestamp: Date.now() - (videos.length - index) * 3600 * 1000
      };
    });
    
    // 获取视频时长
    Promise.all(processedData.map(item => {
      return new Promise(resolve => {
        const video = document.createElement('video');
        video.onloadedmetadata = () => {
          item.duration = video.duration;
          resolve();
        };
        video.onerror = () => {
          console.warn('无法获取视频时长:', item.name);
          item.duration = 0;
          resolve();
        };
        video.src = item.url;
      });
    })).then(() => {
      // 排序和采样
      processedData.sort((a, b) => a.timestamp - b.timestamp);
      
      const sampledData = [];
      for (let i = 0; i < processedData.length; i += Math.ceil(processedData.length / 20)) {
        sampledData.push(processedData[i]);
      }
      
      videoData.value = sampledData;
      
      if (sampledData.length > 0) {
        selectedVideoUrl.value = sampledData[0].url;
      }
      
      initChart();
    });
  } catch (error) {
    console.error('处理文件夹选择时出错:', error);
    errorMessage.value = '处理文件时出错，请重试';
  }
};

// 初始化图表 (保持原有代码不变)
const initChart = () => {
  if (!chartContainer.value || videoData.value.length === 0) return;
  
  if (window.videoLineChart) {
    window.videoLineChart.destroy();
  }
  
  const lineChart = new Line(chartContainer.value, {
    data: videoData.value,
    xField: 'timestamp',
    yField: 'size',
    xAxis: {
      type: 'time',
      tickCount: 5,
      label: {
        formatter: (time) => new Date(time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
        style: {
          fill: '#fff',
          rotate: 45
        }
      },
      grid: {
        line: {
          style: {
            stroke: '#333'
          }
        }
      }
    },
    yAxis: {
      title: {
        text: '视频大小 (MB)',
        style: {
          fill: '#fff'
        }
      },
      label: {
        style: {
          fill: '#fff'
        }
      }
    },
    tooltip: {
      title: (item) => new Date(item.timestamp).toLocaleString('zh-CN'),
      items: [
        { name: '视频名称', value: (item) => item.name },
        { name: '大小', value: (item) => `${item.size.toFixed(2)} MB` },
        { name: '时长', value: (item) => item.duration ? 
          `${Math.floor(item.duration / 60)}:${(item.duration % 60).toString().padStart(2, '0')}` : '未知' }
      ],
      domStyles: {
        'g2-tooltip': {
          backgroundColor: '#1e293b',
          color: '#fff',
          borderColor: '#475569',
          borderRadius: '6px'
        },
        'g2-tooltip-title': {
          color: '#e2e8f0',
          fontWeight: 'bold'
        },
        'g2-tooltip-list-item': {
          color: '#cbd5e1'
        }
      }
    },
    point: {
      size: 6,
      shape: 'circle',
      style: {
        fill: '#fff',
        stroke: '#3b82f6',
        lineWidth: 2,
        cursor: 'pointer'
      }
    },
    interactions: [
      { type: 'marker-active' },
      {
        type: 'element-click',
        callback: ({ data }) => {
          if (data && data?.data?.url) {
            selectedVideoUrl.value = data.data.url;
          }
        }
      }
    ],
    animation: {
      appear: {
        animation: 'wave-in',
        duration: 3000
      }
    },
    theme: {
      colors10: ['#3b82f6']
    }
  });
  
  lineChart.render();
  window.videoLineChart = lineChart;
};

// 组件卸载时释放资源 (保持原有代码不变)
const onUnmounted = () => {
  if (window.videoLineChart) {
    window.videoLineChart.destroy();
  }
  
  objectURLs.value.forEach(url => {
    URL.revokeObjectURL(url);
  });
};

// 生命周期钩子 (保持原有代码不变)
onMounted(() => {
  // 如果不需要初始加载数据，可以移除这行
  // initChart();
});
</script>

<style lang="less" scoped>
// 保持原有样式不变，添加错误消息样式
.error-message {
  color: #ef4444;
  font-size: 10px;
  margin-top: 1px;
  display: flex;
  align-items: center;
}
</style>